home *** CD-ROM | disk | FTP | other *** search
- /****************************************************************************/
- /* */
- /* Module: getopt.c - Get option letter from argument vector */
- /* */
- /* Programmer: Uncertain. From USENET, modified by Jawhar Bammi and */
- /* George R. Woodside. */
- /* */
- /* Date: December 11, 1986 */
- /* */
- /* Function: Parses options in a command line, according to */
- /* an input parameter string. */
- /* */
- /* The input string should be a list of flags to parse for. */
- /* Flags followed by a colon require an extra option value. */
- /* Parsing stops when an argument with no leading dash is */
- /* encountered. */
- /* */
- /* Returns: Each detected flag. Normally, these will be processed in */
- /* the calling program by a switch statement. If the flag had */
- /* a following colon, the option argument is identified by */
- /* the char pointer optarg. If an unidentified flag is */
- /* encountered, getopt prints an error message. When an */
- /* argument with no leading hyphen terminates parsing, the */
- /* array index of that argument is left in optind. */
- /* */
- /* Sample: while( (c=getopt(argc,argv,"ABabC:D:c:d:")) != EOF) */
- /* { */
- /* switch(c) */
- /* { */
- /* case : */
- /* */
- /* */
- /* A command line of "prog -a -c foo extra" would then return */
- /* cases of a and c, with c having optarg foo. optind would */
- /* have a value of 4, indicating that argv[4] ("extra") */
- /* was not processed. */
- /* */
- /****************************************************************************/
-
- #include <stdio.h>
-
- #define BADCH (int)'?'
- #define EMSG ""
- #define tell(s) printf((char *)*nargv); \
- printf((char *)s); \
- printf("%c\n",optopt); \
- return(BADCH);
-
-
- char *optarg; /* argument to return */
-
- int optind = 1; /* index to argv vector */
- int optopt; /* character checked */
-
- int getopt(nargc,nargv,ostr)
- int nargc;
- char **nargv;
- char *ostr;
-
- {
- static char *place = EMSG; /* option letter processing */
- register char *oli; /* option letter list index */
- extern char *index();
-
- if(!*place)
- { /* update scanning pointer */
- if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place)
- return(EOF);
-
- if (*place == '-')
- { /* found "--" */
- ++optind;
- return(EOF);
- }
- } /* option letter okay? */
-
- if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt)))
- {
- if(!*place) ++optind;
- tell(": illegal option -- ");
- }
-
- if (*++oli != ':')
- { /* don't need argument */
- optarg = (char *)NULL;
- if (!*place) ++optind;
- }
- else
- { /* need an argument */
- if (*place)
- optarg = place; /* no white space */
- else if (nargc <= ++optind)
- { /* no arg */
- place = EMSG;
- tell(": option requires an argument -- ");
- }
- else
- optarg = nargv[optind]; /* white space */
- place = EMSG;
- ++optind;
- }
- return(optopt); /* dump back option letter */
- }
-